package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handlerException(SQLIntegrityConstraintViolationException exception){
      log.error(exception.getMessage(),exception);
      if(exception.getMessage().contains("Duplicate entry")){
          String errorMessage = exception.getMessage().split(" ")[2];
          return R.error(errorMessage +"已存在");
      }
            return R.error("请稍后再试");
    }

    /**
     * 错误类型
     * @param exception
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R handlerException(CustomException exception){
        log.info(exception.getMessage(),exception);
        //返回错误信息
        return R.error(exception.getMessage());
    }
}
